package dao

import (
	"context"
	"strings"
	"system-admin/internal/dal"
	"system-admin/internal/models"

	"gorm.io/gen/field"
)

type User struct{}

// UserList 用户列表
func (User) UserList(ctx context.Context, query *dal.Query, merchantID int64) ([]*models.User, error) {
	u := dal.User
	tx := u.WithContext(ctx)
	if merchantID != 0 {
		tx = tx.Where(field.NewInt64(u.TableName(), u.MerchantID.ColumnName().String()).Eq(merchantID))
	}
	return tx.Select(u.ID, u.Username).Find()
}

// ListByUserMerchantPath 获取用户列表，通过商户路径
func (User) ListByUserMerchantPath(
	ctx context.Context,
	query *dal.Query,
	userMerchantPath string,
) ([]*models.User, error) {
	u := query.User
	// 如果是系统管理状态，则返回全部用户
	if userMerchantPath == ">1" {
		list, _ := u.WithContext(ctx).Find()
		if len(list) <= 0 {
			return []*models.User{}, nil
		}
		return list, nil
	}
	// 获取当前用户商户路径
	merchantList, _ := Merchant{}.ListByMerchantPath(ctx, query, userMerchantPath)
	// 获取子商户id，包括自己
	merchantIDs := []string{}
	for _, record := range merchantList {
		merchantIDs = append(merchantIDs, record.ID)
	}
	// 获取子商户用户列表
	merchantArr := strings.Split(userMerchantPath, ">")
	tx := u.WithContext(ctx)
	if len(merchantIDs) > 0 {
		tx = tx.Where(u.MerchantID.In(merchantIDs...))
	}
	if len(merchantArr) > 0 {
		tx = tx.Or(u.MerchantID.Eq(merchantArr[len(merchantArr)-1]))
	}
	list, _ := tx.Find()
	if len(list) <= 0 {
		return []*models.User{}, nil
	}
	return list, nil
}
